package juntos.lbcv.thread;

import java.util.List;

import juntos.lbcv.dao.AlertDAO;
import juntos.lbcv.model.Alert;
import juntos.lbcv.model.AlertAnnonce;
import juntos.lbcv.model.Annonce;
import juntos.lbcv.utils.Lbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Component
@Scope("prototype")
public class CheckAlertTask implements Runnable {

	@Autowired
	AlertDAO alertDAO;
	
	boolean catchAnnonces = true ;
	
	public void catchAnnoncesForAlerts() {
		alertDAO.beginTransaction();
		List<Annonce> annonces = alertDAO.findAllNewAnnonce(Lbc.getDateWithoutTime());
		List<Alert> alerts = alertDAO.findAllAlert();
		for(Annonce annonce:annonces){
			for(Alert alert: alerts){
				if(alertDAO.isAnnonceLikeAlert(annonce,alert)){
					AlertAnnonce alertAnnonce = new AlertAnnonce(annonce, alert,0);
					alertDAO.persitAlertAnnonce(alertAnnonce);
				}
			}
			annonce.setStatut(1);
		}
		alertDAO.commit();
	}

	@Override
	public void run() {
			while(catchAnnonces){
				this.catchAnnoncesForAlerts();
				Lbc.waitXSecondes(60);
			}
	}
}
